package com.hz.winnie.demands.utils;

import java.io.IOException;
import java.io.StringWriter;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonHelper {
    private static ObjectMapper toJSONMapper = new ObjectMapper();
    public static ObjectMapper fromJSONMapper = new ObjectMapper();
    static {
	fromJSONMapper
		.configure(
			DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
			false);
    }

    public static String toJSON(Object obj) {
	ObjectMapper mapper = toJSONMapper;
	StringWriter writer = new StringWriter();
	try {
	    mapper.writeValue(writer, obj);
	} catch (JsonGenerationException e) {
	    throw new RuntimeException(e);
	} catch (JsonMappingException e) {
	    throw new RuntimeException(e);
	} catch (IOException e) {
	    throw new RuntimeException(e);
	}
	return writer.toString();
    }

    public static <T> T fromJSON(String json, Class<T> clazz) {
	ObjectMapper mapper = fromJSONMapper;
	try {
	    return mapper.readValue(json, clazz);
	} catch (JsonParseException e) {
	    throw new RuntimeException(e);
	} catch (JsonMappingException e) {
	    throw new RuntimeException(e);
	} catch (IOException e) {
	    throw new RuntimeException(e);
	}
    }

}
